package com.example.myapplication.api

import android.util.Log
import com.example.myapplication.api.RetrofitFactory.API_KEY
import com.example.myapplication.data.Forecast
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.*

class WeatherRepository(private val api: WeatherApi) {

    suspend fun getWeatherForCity(city: String, date: String): Forecast {
        val response = api.getWeatherForCity(city, API_KEY, date = date)
        return if (response.status == 1 && response.forecasts.isNotEmpty() && response.forecasts[0].casts.isNotEmpty()) {
            val forecast = response.forecasts[0]
            return forecast
        } else {
            throw Exception("Failed to get weather data for city=$city, date=$date")
        }
    }

    suspend fun getExtraWeather(): List<Forecast> {
        val weatherList = mutableListOf<Forecast>()
        val cities = listOf("北京", "上海", "广州", "深圳", "苏州", "沈阳")
        // 获取当前日期和明天的日期
        val today = LocalDate.now()
        val tomorrow = today.plusDays(1)
        var date = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(Date().time + 24 * 60 * 60 * 1000)
        for (city in cities) {
            try {
                val weather = getWeatherForCity(city, date)
                weatherList.add(weather)
            } catch (e: Exception) {
                Log.e("WeatherRepository", e.message.toString())
            }
        }
        return weatherList
    }

}
